var express = require("express")
var router = express.Router()
var QcloudSms = require("qcloudsms_js")
var connection = require("../../../db/sql")
var jwt = require("jsonwebtoken")
const bcrypt = require("bcryptjs")

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" })
})

// 短信验证码接口
router.post("/api/users/code", function (req, res, next) {
  let tel = req.body.phone

  // 短信应用SDK AppID
  var appid = 1400738857 // SDK AppID是1400开头
  // var appid =

  // 短信应用SDK AppKey
  var appkey = "a17ddbf79f6ee7996a8aef7dcedd3224"

  // 需要发送短信的手机号码
  var phoneNumbers = [tel]

  // 短信模板ID，需要在短信应用中申请
  var templateId = 1629161 // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

  // 签名
  var smsSign = "小刘的忧郁个人网" // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

  // 实例化QcloudSms
  var qcloudsms = QcloudSms(appid, appkey)

  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback(err, ress, resData) {
    if (err) {
      console.log("err: ", err)
    } else {
      console.log("request data: ", ress.req)
      console.log("response data: ", resData)
    }
  }

  var ssender = qcloudsms.SmsSingleSender()
  // 这个变量params发送到手机的短信
  var params = [Math.floor(Math.random() * (9999 - 1000) + 1000)]
  ssender.sendWithParam(
    86,
    phoneNumbers[0],
    templateId,
    params,
    smsSign,
    "",
    "",
    callback
  ) // 签名参数不能为空串

  res.send({
    data: {
      code: params,
    },
  })
})

// 短信验证登录接口
router.post("/api/users/messagelogin", function (req, res, next) {
  // 参数,phone
  let phone = req.body.phone
  // 根据phone生成token
  let play = { tel: phone }
  let secert = "liulin"
  // let token = jwt.sign(play, secert, { expiresIn: 5 })
  let token = jwt.sign(play, secert)
  console.log(token)
  connection.query(
    `select * from user where user_phone=${phone}`,
    function (err, reslut) {
      if (reslut.length > 0) {
        delete reslut[0].user_id
        delete reslut[0].user_phone
        delete reslut[0].user_password
        res.send({
          status: 200,
          data: reslut,
          msg: "查询到该用户",
          token,
        })
      } else {
        res.send({
          status: 405,
          data: reslut,
          msg: "该用户没有注册",
        })
      }
    }
  )
})

// 密码登录接口
router.post("/api/users/passwordLogin", function (req, res, next) {
  let phone = req.body.phone
  let password = req.body.password
  // 根据phone生成token
  let play = { tel: phone }
  let secert = "liulin"
  // let token = jwt.sign(play, secert, { expiresIn: 5 })
  let token = jwt.sign(play, secert)
  console.log(phone, password)
  // 根据号码查询用户
  connection.query(
    `select * from user where user_phone=${phone}`,
    function (err, results) {
      if (err) {
        res.send({
          status: 306,
          erroe: err,
        })
      } else if (results.length != 0) {
        // 拿着用户输入的密码,和数据库中存储的密码进行对比
        console.log(results)
        const compareResult = bcrypt.compareSync(
          password,
          results[0].user_password
        )
        if (compareResult) {
          delete results[0].user_id
          delete results[0].user_phone
          delete results[0].user_password
          res.send({
            status: 412,
            msg: "登录成功",
            token: token,
            data: results,
          })
        } else {
          res.send({
            status: 418,
            msg: "密码不正确",
          })
        }
      } else {
        res.send({
          status: 406,
          msg: "用户不存在",
        })
      }
    }
  )
})

// 注册接口
router.post("/api/users/register", function (req, res, next) {
  let data = req.body
  console.log(data.phone)
  // 对用户的密码,进行 bcrype 加密，返回值是加密之后的密码字符串
  let password = bcrypt.hashSync(data.password, 10)
  let username = "账号" + new Date().getTime()
  connection.query(
    `select * from user where user_phone= ${data.phone}`,
    function (err, reslut) {
      if (err) {
        res.send({
          status: 409,
          err,
          msg: "错误",
        })
      } else if (reslut.length != 0) {
        res.send({
          status: 407,
          msg: "账号已经注册",
        })
      } else {
        connection.query(
          'insert into user (user_phone,user_password,user_name) values("' +
            data.phone +
            '" ,"' +
            password +
            '","' +
            username +
            '")',
          function (err, reslut) {
            if (err) {
              res.send({
                msg: "错误",
                err,
              })
            } else {
              res.send({
                status: 200,
                meg: "注册成功",
              })
            }
          }
        )
      }
    }
  )
})

// 忘记密码接口
router.post("/api/users/forgetPassword", function (req, res, next) {
  let data = req.body
  console.log(data)
  // 判断用户是否存在
  connection.query(
    `select * from user where user_phone= ${data.phone}`,
    function (err, resluts) {
      if (err) {
        res.send({
          status: 409,
          msg: "出错",
          err,
        })
      } else {
        if (resluts.length > 0) {
          let password = JSON.stringify(bcrypt.hashSync(data.password, 10))
          console.log(password)
          connection.query(
            `UPDATE user set user_password=${password.toString()} WHERE user_phone=${
              data.phone
            }
          `,
            function (err, resluts) {
              if (err) {
                res.send({
                  status: 410,
                  msg: "出错",
                  err,
                })
              } else {
                res.send({
                  status: 200,
                  msg: "更新密码成功",
                })
              }
            }
          )
        } else {
          res.send({
            status: 407,
            msg: "账号未注册",
          })
        }
      }
    }
  )
})

// get测试数据
router.get("/api/users/loginsuccess", function (req, res, next) {
  res.send({
    status: 200,
    msg: "成功",
  })
})

// post测试数据
// router.post("/api/resgister", function (req, res, next) {
//   let data = req.body
//   console.log("获取到前端数据" + data.name, data.age)
//   connection.query("select * from user", function (err, reslut) {
//     if (err) {
//       res.send({
//         status: 444,
//         msg: "失败",
//       })
//     }
//     res.send({
//       status: 200,
//       data: reslut,
//       msg: "成功",
//     })
//   })
// })

module.exports = router
